// vue.config.js的基础配置
const CompressionPlugin = require('compression-webpack-plugin')

// npm run build后，打开localhost:8888，项目结构
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

// const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const path = require("path");
// 自动补全css前缀的东西 别忘了npm install postcss, npm install autoprefixer
const autoprefixer = require('autoprefixer')
// px 转换 rem单位
const pxtorem = require('postcss-pxtorem')
// 移除log 压缩js
const TerserPlugin = require("terser-webpack-plugin");
const debug = process.env.NODE_ENV === "production";
const TimeStamp = parseInt(new Date().getTime() / 1000);
function resolve (dir) {
  return path.join(__dirname, dir)
}



const webpack = require('webpack')
// 引入等比适配插件
const px2rem = require('postcss-px2rem')

// 配置基本大小
const postcss = px2rem({
  // 基准大小 baseSize，需要和rem.js中相同
  remUnit: 16
})


const cdn = {
  css: [
    // element-ui css
    // 'https://cdn.bootcss.com/element-ui/2.12.0/theme-chalk/index.css',
    // 'https://cdnjs.cloudflare.com/ajax/libs/element-ui/2.12.0/theme-chalk/index.min.css',
  ],
  js: [
    // vue must at first!
    // 'https://cdn.bootcss.com/vue/2.6.10/vue.min.js',
    // "https://cdn.staticfile.org/vue-router/2.7.0/vue-router.min.js",
    // "https://cdn.bootcss.com/vuex/3.1.0/vuex.min.js",
    // "https://cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.min.js",
    // // "https://cdn.bootcss.com/element-ui/2.4.5/index.js",
    // "https://cdn.bootcdn.net/ajax/libs/element-ui/2.12.0/index.js",
    // "https://cdn.bootcdn.net/ajax/libs/xlsx/0.15.4/xlsx.core.min.js",
  ],
  externals: {
    // 'echarts': 'echarts',
    // "html2canvas": "html2canvas",
    // 'axios': 'axios',
    // 'vue-router': 'VueRouter',
    // 'element-ui': 'ELEMENT',
    // 'vue': 'Vue',
    // 'vuex': 'Vuex',
    // 'xlsx': 'XLSX',
  }
}



module.exports = {

  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "@/style/method.scss";`
      },
      postcss: {
        plugins: [
          autoprefixer({
            //   browsers: ['Android >= 4.0', 'iOS >= 7']
            browsers: ['last 10 Chrome versions', 'last 5 Firefox versions', 'Safari >= 6', 'ie> 8']
          }),

          // postcss,


          // pxtorem({
          //   rootValue: 19.2,
          //   propList: ['*']
          // })

        ]
      }
    }
  },
  //jq配置  wtl
  chainWebpack: config => {

    config.plugin('provide').use(webpack.ProvidePlugin, [
      {
        $: 'jquery',
        jquery: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      }
    ])


    // 字体文件处理 指定 /static/fonts/[name].[ext]
    config.module
        .rule("fonts")
        .test(/.(ttf|otf|eot|woff|woff2)$/)
        .use("url-loader")
        .loader("url-loader")
        .tap(options => {
          options = {
            name: 'static/fonts/[name].[ext]',
          }
          return options
        }).end();
    debug && config.plugin('extract-css').tap(args => [{
      filename: `static/css/[name].[hash].${TimeStamp}.css`,
      chunkFilename: `static/css/[name].[hash].${TimeStamp}.css`
    }])

    config.resolve.alias
        .set('@', resolve('src'))
        .set('@a', resolve('src/assets'))
        .set('@c', resolve('src/components'))
        .set('@p', resolve('src/plugins'))
        .set('@u', resolve('src/util'))
        .set('@r', resolve('src/router'))
        .set('@s', resolve('src/store'))
        .set('@v', resolve('src/views'));

    config.plugin('html').tap(args => {
      if(debug) {
        args[0].cdn = cdn
      }
      args[0].title = 'CGA管理系统'
      return args
    })


      // ============压缩图片 start============
      //debug && config.module
      //     .rule('images')
      //     .use('image-webpack-loader')
      //     .loader('image-webpack-loader')
      //     .options({ bypassOnDebug: true })
      //     .end()
    debug && config.externals(cdn.externals)

  },


  configureWebpack: config => {
    if (debug) {
      return {
        output: {
          // 输出重构  打包编译后的 文件名称  【模块名称.版本号.时间戳】
          filename: `static/js/[name].[hash].${TimeStamp}.js`,
          chunkFilename: `static/js/[name].[hash].${TimeStamp}.js`
        },

        optimization: {
          minimizer: [
            // new CompressionPlugin({
            //   algorithm: 'gzip',//开启gzip
            //   test: /\.js$|\.html$|.\css/, // 匹配文件名
            //   threshold: 10240, // 对超过10k的数据压缩
            //   deleteOriginalAssets: false // 不删除源文件
            // }),
            // new TerserPlugin({
            //   terserOptions: {
            //     ecma: undefined,
            //     warnings: false,
            //     parse: {},
            //     compress: {
            //       drop_console: true,
            //       drop_debugger: false,
            //       pure_funcs: ['console.log'] // 移除console
            //     }
            //   }
            // }),
          ],
          // 开启分离js
          runtimeChunk: 'single',
          splitChunks: {
            chunks: 'all',
            maxInitialRequests: Infinity,
            minSize: 20000,
            cacheGroups: {
              vendor: {
                test: /[\\/]node_modules[\\/]/,
                name (module) {
                  // get the name. E.g. node_modules/packageName/not/this/part.js
                  // or node_modules/packageName
                  const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                  // npm package names are URL-safe, but some servers don't like @ symbols
                  return `npm.${packageName.replace('@', '')}`
                }
              }
            }
          }
        },
        plugins: [
          // ...config.plugins,
          // 代码压缩
          // new TerserPlugin({
          //   terserOptions: {
          //     ecma: undefined,
          //     warnings: false,
          //     parse: {},
          //     compress: {
          //       drop_console: true,
          //       drop_debugger: false,
          //       pure_funcs: ['console.log'] // 移除console
          //     }
          //   }
          // }),
          // new BundleAnalyzerPlugin(),
          // new CompressionPlugin({
          //   algorithm: 'gzip',//开启gzip
          //   test: /\.js$|\.html$|.\css/, // 匹配文件名
          //   threshold: 10240, // 对超过10k的数据压缩
          //   deleteOriginalAssets: false // 不删除源文件
          // })
        ]

        // plugins: [
        // 代码压缩
        // new UglifyJsPlugin({
        //   uglifyOptions: {
        //     //生产环境自动删除console
        //     compress: {
        //       // warnings: false, // 若打包错误，则注释这行
        //       drop_debugger: true,
        //       drop_console: true,
        //       pure_funcs: ['console.log']
        //     }
        //   },
        //   sourceMap: false,
        //   parallel: true
        // })
        // ],

      }

    }
  },

  devServer: {
    port: 9090,
    disableHostCheck: true,
    open: true,
    proxy: {
      "/webApi": {
        target: "https://khrhser.apppsy.com/",
        ws: true,
        changeOrigin: true, // 容许跨域
        pathRewrite: {
          "^/webApi": ""
        }
      },
    }
  },


    lintOnSave: false,
    runtimeCompiler: true, // 关键点在这
    publicPath: "./", // ./改为/
    outputDir: "dist",
    // assetsDir: "static",
    assetsDir: "https://apidoc.gitee.com/sunwxm/by-ggl/dist/static",
    indexPath: "index.html",
    // productionSourceMap: false,
    filenameHashing: true,
}
